package com.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class UploadUtils {
	
	public static List<String> uploadImg(MultipartFile[] imgfiles, String imgUploadPath, String imgAccessPath) throws Exception {
		List<String> imgpaths = new ArrayList<String>();
		if ((imgfiles != null) && (imgfiles.length > 0)) {
			for (int i = 0; i < imgfiles.length; i++) {
				MultipartFile img = imgfiles[i];
				long nowts = System.currentTimeMillis();//毫秒数
				String ptyp = FileUtils.getFileType(img.getOriginalFilename());//文件后缀
				String realrootdic = imgUploadPath + File.separator + DateUtils.getCurrentDateStr();//图片存放路径
				String picrealpath = realrootdic + File.separator +  i + nowts + "." + ptyp.toLowerCase();//图片存放全路径
				String picAccRootdic = imgAccessPath + File.separator + DateUtils.getCurrentDateStr();//图片访问路径
				String picAccessPath = picAccRootdic + File.separator +  i + nowts + "." + ptyp.toLowerCase();//图片访问全路径
				//创建文件夹
				FileUtils.createFile(realrootdic);
				//上传文件
				uploadfile(img, picrealpath);
				//往集合里存放数据
				imgpaths.add(picAccessPath);
			}
		}
		return imgpaths;
	}

	private static void uploadfile(MultipartFile img, String filepath) throws IllegalStateException, IOException {
		File file = new File(filepath);
		img.transferTo(file);
	}
	
	public static List<String> uploadQiniuImg(MultipartFile[] imgfiles, String imgUploadPath, String imgAccessPath) throws Exception {
		List<String> imgpaths = new ArrayList<String>();
		
		String accessKey = "g17ewr7db96TeSCVv31Tjf6ed3lLt8Pz_SgL4-Cq";
		String secretKey = "KaNFtVwFhxBDLLGqFr6cbeB7YpYX8niBjwKj4dKF";
		String bucket = "tielu";
		
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone1());
		UploadManager uploadManager = new UploadManager(cfg);
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		if(imgfiles!=null) {
			for(int i = 0; i < imgfiles.length; i++) {
				
				MultipartFile img = imgfiles[i];
				long nowts = System.currentTimeMillis();//毫秒数
				String ptyp = FileUtils.getFileType(img.getOriginalFilename());//文件后缀
				String picrealpath = i + nowts + "." + ptyp.toLowerCase();//图片存放名称
				
				Response response = uploadManager.put(imgfiles[i].getBytes(), picrealpath, upToken);
				//解析上传成功的结果
		        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		        System.out.println(putRet.key);
		        System.out.println(putRet.hash);
		        imgpaths.add(imgAccessPath + "/" + putRet.key);
			}
		}
		return imgpaths;
	}
}
